package com.wulian.common.util;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.wulian.common.util.DateUtil;

/**
 * <p>
 *
 * </p>
 *
 * @author shaoshuang
 * @since 2018/8/16 15:23
 */
public class MyDateFormat extends DateFormat{
    private DateFormat dateFormat;

    public MyDateFormat(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return dateFormat.format(date, toAppendTo, fieldPosition);
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        Date date = null;
        try {
            date = DateUtil.sdf.parse(source, pos);
        } catch (Exception e) {
            date = dateFormat.parse(source, pos);
        }
        return date;
    }

    // 主要还是装饰这个方法
    @Override
    public Date parse(String source) throws ParseException {
        SimpleDateFormat sdf = DateUtil.sdf;
        Date date = null;
        try {
            // 先按我的规则来
            if (StringUtils.contains(source, " ")) {
                date = sdf.parse(source);
            }
            else {
                date = new Date(Long.parseLong(source));
            }
        } catch (Exception e) {
            // 不行，那就按原先的规则吧
            date = dateFormat.parse(source);
        }
        return date;
    }

    // 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
    @Override
    public Object clone() {
        Object format = dateFormat.clone();
        return new MyDateFormat((DateFormat) format);
    }



}
